package com.application.sistercityapplication.main;


import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import antistatic.spinnerwheel.AbstractWheel;
import antistatic.spinnerwheel.OnWheelChangedListener;
import antistatic.spinnerwheel.adapters.AbstractWheelTextAdapter;

import com.application.sistercityapplication.cityinformationpage.CityInformationListAdapter;
import com.application.sistercityapplication.dto.ContactDto;
import com.application.sistercityapplication.dto.InformationMasterDto;
import com.application.sistercityapplication.dto.MagazineDto;
import com.application.sistercityapplication.dto.NewsDto;
import com.application.sistercityapplication.gallery.AppConstant;
import com.application.sistercityapplication.gallery.GridViewImageAdapter;
import com.application.sistercityapplication.gallery.Utils;
import com.application.sistercityapplication.json.JSONParserForGetList;
import com.application.sistercityapplication.listadapter.ContactListAdapter;
import com.application.sistercityapplication.listadapter.DocumentListAdapter;
import com.application.sistercityapplication.mappage.FullScreenMapViewActivity;
import com.application.sistercityapplication.model.Magazine;
import com.application.sistercityapplication.news.NewsListAdapter;
import com.application.sistercityapplication.utils.GlobalVariable;
import com.application.sistercityapplication.utils.SwipeDismissListViewTouchListener;
import com.roscopeco.ormdroid.Entity;

public class MainHomePageViewActivity extends Activity {

	private AbstractWheel logoShelfListView;
	private Button btn_map, btn_information, btn_gallery, btn_news,btn_document,btn_photos;
	private FrameLayout mainLayout;
	private LayoutInflater inflater;
	private ListView lv,docList,contactList;
	private GlobalVariable gbv;
	private CountryAdapter cta;
	private Utils utils;
	private GridView gridView;
	private int columnWidth;
	private GridViewImageAdapter adapter;
	private List<String> imagePaths = new ArrayList<String>();
	private static int currentPage=11;
	private String stage;
	private ProgressBar pBar;
	private View informationView;
	private View v;
	boolean isCurrentHomePage;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isCurrentHomePage = Boolean.parseBoolean(getIntent().getStringExtra("isCurrentPage"));
		gbv = new GlobalVariable();
		if (gbv.checkScreenSize(getApplicationContext()) == 2) {
			setContentView(R.layout.main_home_page_view_layout_large);
			cta = new CountryAdapter(getApplicationContext(), R.layout.country_centered_large);
		} else {
			setContentView(R.layout.main_home_page_view_layout);
			cta = new CountryAdapter(getApplicationContext(), R.layout.country_centered);
		}
		super.onCreate(savedInstanceState);
		mainLayout = (FrameLayout) findViewById(R.id.frameForInflate);
		inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		v = inflater.inflate(R.layout.android_home_inflate, null);
		mainLayout.addView(v);
		
		logoShelfListView = (AbstractWheel) findViewById(R.id.flagLogoList);
		
		logoShelfListView.setViewAdapter(cta);
		logoShelfListView.setCurrentItem(currentPage);
		logoShelfListView.setCyclic(true);
		btn_map = (Button) v.findViewById(R.id.btn_map);
		btn_map.setOnClickListener(new BtnMapListener());
		btn_information = (Button) v.findViewById(R.id.btn_information);
		btn_information.setOnClickListener(new BtnInformationListener());
		btn_gallery = (Button) v.findViewById(R.id.btn_gallery);
		btn_gallery.setOnClickListener(new BtnGalleryListener());
		btn_news = (Button) v.findViewById(R.id.btn_places);
		btn_news.setOnClickListener(new BtnNewsIstener());
		btn_document = (Button) v.findViewById(R.id.btn_messages);
		btn_document.setOnClickListener(new BtnDocumentListener());
		btn_photos = (Button) v.findViewById(R.id.btn_photos);
		btn_photos.setOnClickListener(new BtnContactPointListener());
		utils = new Utils(this);
		
		logoShelfListView.addChangingListener(new OnWheelChangedListener(){

			@Override
			public void onChanged(AbstractWheel wheel, int oldValue,
					int newValue) {
				if(stage!=null && !stage.equals("")){
					if("contact".equals(stage)){
						new DownloadContactTask(getApplicationContext(),MainHomePageViewActivity.this,pBar).execute();
					}else if("doc".equals(stage)){
						new DownloadDocumentTask(getApplicationContext(),MainHomePageViewActivity.this,pBar).execute();
					}else if("info".equals(stage)){
						List<InformationMasterDto> listNews = new ArrayList<InformationMasterDto>();
						new DownLoadInfoTask(getApplicationContext(),listNews,MainHomePageViewActivity.this,pBar).execute();
					}else if("gal".equals(stage)){
						
						new DownLoadGalleryTask(getApplicationContext(),imagePaths,MainHomePageViewActivity.this,pBar).execute();

					}else if("news".equals(stage)){
						List<NewsDto> listNews = new ArrayList<NewsDto>();
						new DownLoadNewsTask(getApplicationContext(),listNews,MainHomePageViewActivity.this,pBar).execute();
					}
						
				}
			}
			
		});
	}
	public class BtnContactPointListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			mainLayout.removeAllViews();
			View documentView = inflater.inflate(R.layout.android_contactpoint_layout, null);
			mainLayout.addView(documentView);
			ImageView back_icon = (ImageView) documentView.findViewById(R.id.back_icon);
			pBar = (ProgressBar) documentView.findViewById(R.id.progress);

			contactList = (ListView) documentView.findViewById(R.id.contactListView);
			
			new DownloadContactTask(getApplicationContext(),MainHomePageViewActivity.this,pBar).execute();
			stage="contact";
			
			back_icon.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent i = new Intent(MainHomePageViewActivity.this,MainSisterCityActivity.class);
					startActivity(i);
					finish();
				}
			});
		}
		
	}
	public class BtnDocumentListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			mainLayout.removeAllViews();
			View documentView = inflater.inflate(R.layout.activity_document_layout, null);
			mainLayout.addView(documentView);
			ImageView back_icon = (ImageView) documentView.findViewById(R.id.back_icon);
			pBar = (ProgressBar) documentView.findViewById(R.id.progress);

			docList = (ListView) documentView.findViewById(R.id.documentListView);
			
			new DownloadDocumentTask(getApplicationContext(),MainHomePageViewActivity.this,pBar).execute();
			stage="doc";
			back_icon.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent i = new Intent(MainHomePageViewActivity.this,
							MainSisterCityActivity.class);
					startActivity(i);
					finish();
				}
			});
			
		}
		
	}
	public class BtnMapListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int countryId = logoShelfListView.getCurrentItem()%11;
			String x = new CountryAdapter(getApplicationContext(), R.layout.country_centered_large).countries[logoShelfListView.getCurrentItem()%11];
			Toast.makeText(getApplicationContext(),String.valueOf(x), Toast.LENGTH_SHORT).show();
			
			Intent i = new Intent(MainHomePageViewActivity.this,FullScreenMapViewActivity.class);
			i.putExtra("countryId", countryId+"");
			i.putExtra("countryName", x);
			startActivity(i);
			
		}

	}
	
	public class BtnInformationListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			mainLayout.removeAllViews();
			informationView = inflater.inflate(R.layout.activity_city_information_main, null);
			mainLayout.addView(informationView);
			ImageView back_icon = (ImageView) informationView.findViewById(R.id.back_icon);
			pBar = (ProgressBar) informationView.findViewById(R.id.progress);
			currentPage = logoShelfListView.getCurrentItem();
			List<InformationMasterDto> listNews = new ArrayList<InformationMasterDto>();
			new DownLoadInfoTask(getApplicationContext(),listNews,MainHomePageViewActivity.this,pBar).execute();
			stage="info";
			back_icon.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent i = new Intent(MainHomePageViewActivity.this,
							MainSisterCityActivity.class);
					startActivity(i);
					finish();
				}
			});

		}

	}

	public class BtnGalleryListener implements OnClickListener {

		@SuppressLint("NewApi")
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			mainLayout.removeAllViews();
			View informationView = inflater.inflate(R.layout.activity_gallery_main, null);
			mainLayout.addView(informationView);
			ImageView back_icon = (ImageView) informationView.findViewById(R.id.back_icon);
//			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//			StrictMode.setThreadPolicy(policy);
			pBar = (ProgressBar) informationView.findViewById(R.id.progress);
			gridView = (GridView) informationView.findViewById(R.id.grid_view);
			InitilizeGridLayout();
			new DownLoadGalleryTask(getApplicationContext(),imagePaths,MainHomePageViewActivity.this,pBar).execute();
			
			stage = "gal";
			back_icon.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent i = new Intent(MainHomePageViewActivity.this,
							MainSisterCityActivity.class);
					startActivity(i);
					finish();
				}
			});
		}

	}

	public class BtnNewsIstener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			mainLayout.removeAllViews();
			View informationView = inflater.inflate(R.layout.main_news_layout,null);
			pBar = (ProgressBar) informationView.findViewById(R.id.progress);
			mainLayout.addView(informationView);
			ImageView back_icon = (ImageView) informationView.findViewById(R.id.back_icon);
			List<NewsDto> listNews = new ArrayList<NewsDto>();
			lv = (ListView) informationView.findViewById(R.id.listNews);
			new DownLoadNewsTask(getApplicationContext(),listNews,MainHomePageViewActivity.this,pBar).execute();
			stage = "news";
			back_icon.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent i = new Intent(MainHomePageViewActivity.this,
							MainSisterCityActivity.class);
					startActivity(i);
					finish();
				}
			});
		}

	}
	public class CountryAdapter extends AbstractWheelTextAdapter {
		// Countries names
		private String countries[] = new String[] {
				getResources().getString(R.string.asean),
				getResources().getString(R.string.brunei),
				getResources().getString(R.string.cambodia),
				getResources().getString(R.string.indonesia),
				getResources().getString(R.string.laos),
				getResources().getString(R.string.malaysia),
				getResources().getString(R.string.philiphines),
				getResources().getString(R.string.singapore),
				getResources().getString(R.string.thailand),
				getResources().getString(R.string.veitnam),
				getResources().getString(R.string.burma),
				getResources().getString(R.string.asean),
				getResources().getString(R.string.brunei),
				getResources().getString(R.string.cambodia),
				getResources().getString(R.string.indonesia),
				getResources().getString(R.string.laos),
				getResources().getString(R.string.malaysia),
				getResources().getString(R.string.philiphines),
				getResources().getString(R.string.singapore),
				getResources().getString(R.string.thailand),
				getResources().getString(R.string.veitnam),
				getResources().getString(R.string.burma)};
		// Countries flags
		private int flags[] = new int[] { R.drawable.asean_flag,
				R.drawable.brunei, R.drawable.cambodia, R.drawable.indo,
				R.drawable.laos, R.drawable.malay, R.drawable.philipins,
				R.drawable.new_singapore, R.drawable.new_thailand, R.drawable.vietnam , R.drawable.mynmar,
				R.drawable.asean_flag,
				R.drawable.brunei, R.drawable.cambodia, R.drawable.indo,
				R.drawable.laos, R.drawable.malay, R.drawable.philipins,
				R.drawable.new_singapore, R.drawable.new_thailand, R.drawable.vietnam , R.drawable.mynmar};
		
		/**
		 * Constructor
		 */
		public CountryAdapter(Context context,int layoutID) {
			//super(context, R.layout.country_centered_large, NO_RESOURCE);
			super(context, layoutID, NO_RESOURCE);
			setItemTextResource(R.id.country_name);
		}


		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			View view = super.getItem(index, cachedView, parent);
			ImageView img = (ImageView) view.findViewById(R.id.flag);
			img.setImageResource(flags[index]);
			return view; 
		}

		@Override
		public int getItemsCount() {
			return countries.length;
		}

		@Override
		protected CharSequence getItemText(int index) {
			return countries[index];
		}
	}
	public class DownLoadNewsTask extends AsyncTask<String, Void, List<NewsDto>> {
		ProgressDialog pDialog;
		private Context context;
		private List<NewsDto> listNews;
		public Activity _activity;
		private ProgressBar _resid;

		public DownLoadNewsTask(Context context, List<NewsDto> view,Activity act,ProgressBar resid) {
			super();
			this.context = context;
			this.listNews = view;
			this._activity = act;
			this._resid = resid;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
//			pDialog = new ProgressDialog(MainHomePageViewActivity.this);
//			pDialog.setMessage("Loading Content...");
//			pDialog.show();
			_resid.setVisibility(View.VISIBLE);
		}

		@Override
		protected List<NewsDto> doInBackground(String... params) {
			JSONParserForGetList json = JSONParserForGetList.getInstance();
			listNews = json.getNews(String.valueOf(logoShelfListView.getCurrentItem()%11 + 1));
			currentPage =  logoShelfListView.getCurrentItem()%11;
			return listNews;
		}

		@Override
		protected void onPostExecute(List<NewsDto> result) {
			super.onPostExecute(result);
//			if (null != pDialog && pDialog.isShowing()) {
//				pDialog.dismiss();
//			}
			_resid.setVisibility(View.GONE);
			if (result != null) {
				NewsListAdapter nla = new NewsListAdapter(listNews,getApplicationContext(), MainHomePageViewActivity.this);
				lv.setAdapter(nla);
			} else {
				(Toast.makeText(context, "An error occured.", Toast.LENGTH_LONG)).show();
			}

		}
	}
	public class DownLoadInfoTask extends AsyncTask<String, Void, List<InformationMasterDto>> {
		ProgressDialog pDialog;
		private Context context;
		private List<InformationMasterDto> listInfo;
		public Activity _activity;
		private ProgressBar _resid;

		public DownLoadInfoTask(Context context, List<InformationMasterDto> view,Activity act,ProgressBar resid) {
			super();
			this.context = context;
			this.listInfo = view;
			this._activity = act;
			this._resid = resid;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
//			pDialog = new ProgressDialog(MainHomePageViewActivity.this);
//			pDialog.setMessage("Loading Content...");
//			pDialog.show();
			_resid.setVisibility(View.VISIBLE);
		}

		@Override
		protected List<InformationMasterDto> doInBackground(String... params) {
			listInfo = JSONParserForGetList.getInstance().getInformations(String.valueOf(logoShelfListView.getCurrentItem()%11 + 1));
			currentPage =  logoShelfListView.getCurrentItem()%11;
			Log.d("com.geting.position", (logoShelfListView.getCurrentItem()%11 + 1)+"");
			return listInfo;
		}

		@Override
		protected void onPostExecute(List<InformationMasterDto> result) {
			super.onPostExecute(result);
//			if (null != pDialog && pDialog.isShowing()) {
//				pDialog.dismiss();
//			}
			_resid.setVisibility(View.GONE);
			if (result != null) {
				ListView informationListView = (ListView) informationView.findViewById(R.id.informationListView);
				CityInformationListAdapter adp = new CityInformationListAdapter(listInfo, getApplicationContext(),MainHomePageViewActivity.this, mainLayout,9+"");
				informationListView.setAdapter(adp);
			} else {
				(Toast.makeText(context, "An error occured.", Toast.LENGTH_LONG)).show();
			}

		}
	}
	public class DownLoadGalleryTask extends AsyncTask<String, Void, List<String>> {
		ProgressDialog pDialog;
		private Context context;
		public Activity _activity;
		private ProgressBar _resid;

		public DownLoadGalleryTask(Context context, List<String> view,Activity act,ProgressBar resid) {
			super();
			this.context = context;
			this._activity = act;
			this._resid = resid;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
//			pDialog = new ProgressDialog(MainHomePageViewActivity.this);
//			pDialog.setMessage("Loading Content...");
//			pDialog.show();
			_resid.setVisibility(View.VISIBLE);
		}

		@Override
		protected List<String> doInBackground(String... params) {
			JSONParserForGetList json = JSONParserForGetList.getInstance();
			//imagePaths = json.getGallerys(String.valueOf(logoShelfListView.getCurrentItem()%11 + 1));
			currentPage = logoShelfListView.getCurrentItem();
			

			return imagePaths;
		}

		@Override
		protected void onPostExecute(List<String> result) {
			super.onPostExecute(result);
//			if (null != pDialog && pDialog.isShowing()) {
//				pDialog.dismiss();
//			}
			_resid.setVisibility(View.GONE);
			if (result != null) {
				//adapter = new GridViewImageAdapter(MainHomePageViewActivity.this, result,columnWidth);
				gridView.setAdapter(adapter);
			} else {
				(Toast.makeText(context, "An error occured.", Toast.LENGTH_LONG)).show();
			}

		}
	}
	public class DownloadDocumentTask extends AsyncTask<String, Void, List<MagazineDto>>{
		ProgressDialog pDialog;
		private Context context;
		public Activity _activity;
		private ProgressBar _resId;
		private boolean isDismiss = false;
		private Magazine mag;
		public DownloadDocumentTask(Context context,Activity act,ProgressBar resid) {
			super();
			this.context = context;
			this._activity = act;
			this._resId = resid;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
//			pDialog = new ProgressDialog(MainHomePageViewActivity.this);
//			pDialog.setMessage("Loading Document...");
//			pDialog.show();
			_resId.setVisibility(View.VISIBLE);
		}
		@Override
		protected List<MagazineDto> doInBackground(String... params) {
			// TODO Auto-generated method stub
			JSONParserForGetList json = JSONParserForGetList.getInstance();
			List<MagazineDto> magList = null;
			magList = json.getMagazines(String.valueOf(logoShelfListView.getCurrentItem()%11 + 1));
			currentPage = logoShelfListView.getCurrentItem();
			return magList;
		}
		@Override
		protected void onPostExecute(List<MagazineDto> result) {
			super.onPostExecute(result);
			_resId.setVisibility(View.GONE);
			final DocumentListAdapter docAdapter = new DocumentListAdapter(result,getApplicationContext(),MainHomePageViewActivity.this);
			
			if (result != null) {
				
				SwipeDismissListViewTouchListener touchListener =
			                new SwipeDismissListViewTouchListener(
			                		docList,
			                        new SwipeDismissListViewTouchListener.DismissCallbacks() {
			                            @Override
			                            public boolean canDismiss(int position) {
			                            	boolean isValid = false;
			                            	MagazineDto dto = (MagazineDto) docList.getItemAtPosition(position);
			                            	mag = Entity.query(Magazine.class).where("magId").eq(dto.getMagId()).execute();
			                    			if(mag!=null){
			                    				isValid = true;
			                    			}else{
			                    				isValid = false;
			                    			}
			                                return isValid;
			                            }

			                            @Override
			                            public void onDismiss(ListView listView, int[] reverseSortedPositions) {
			                            	
			                                for (int position : reverseSortedPositions) {
			                                    //mAdapter.remove(mAdapter.getItem(position));
			                                	//docAdapter.
			                                	View view = docList.getChildAt(position);
			                                	final ImageView deleteBt =  (ImageView) view.findViewById(R.id.deleteBookBtn);
			                                	final ImageView dowloadBt =  (ImageView) view.findViewById(R.id.downLoadBookBtn);
			                                	if(!isDismiss){
			                                	deleteBt.setVisibility(View.VISIBLE);
			                                	isDismiss = true;
			                                	deleteBt.setOnClickListener(new OnClickListener() {
													
													@Override
													public void onClick(View v) {
														mag.delete();
														deleteBt.setVisibility(View.GONE);
														dowloadBt.setVisibility(View.VISIBLE);
														docAdapter.notifyDataSetChanged();
													}
												});
			                                	}else{
			                                	deleteBt.setVisibility(View.GONE);
				                                isDismiss = false;	
			                                	}
			                                }
			                                docAdapter.notifyDataSetChanged();
			                            }
			                        });
				docList.setOnTouchListener(touchListener);
				docList.setAdapter(docAdapter);
			} else {
				(Toast.makeText(context, "An error occured.", Toast.LENGTH_LONG)).show();
			}

		}
		
	}
	public class DownloadContactTask extends AsyncTask<String, Void, List<ContactDto>>{
		ProgressDialog pDialog;
		private Context context;
		public Activity _activity;
		private ProgressBar _resId;
		public DownloadContactTask(Context context,Activity act,ProgressBar resid) {
			super();
			this.context = context;
			this._activity = act;
			this._resId = resid;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			_resId.setVisibility(View.VISIBLE);
		}
		@Override
		protected List<ContactDto> doInBackground(String... params) {
			// TODO Auto-generated method stub
			JSONParserForGetList json = JSONParserForGetList.getInstance();
			List<ContactDto> contactList = json.getContacts(String.valueOf(logoShelfListView.getCurrentItem()%11 + 1));
			currentPage = logoShelfListView.getCurrentItem();
			return contactList;
		}
		@Override
		protected void onPostExecute(List<ContactDto> result) {
			super.onPostExecute(result);
			_resId.setVisibility(View.GONE);
			ContactListAdapter conAdapter = new ContactListAdapter(result,getApplicationContext(),MainHomePageViewActivity.this);
			contactList.setAdapter(conAdapter);
			if (result != null) {
				
			} else {
				(Toast.makeText(context, "An error occured.", Toast.LENGTH_LONG)).show();
			}

		}
		
	}
	private void InitilizeGridLayout() {
		Resources r = getResources();
		float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,AppConstant.GRID_PADDING, r.getDisplayMetrics());

		columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);

		gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
		gridView.setColumnWidth(columnWidth);
		gridView.setStretchMode(GridView.NO_STRETCH);
		gridView.setPadding((int) padding, (int) padding, (int) padding,
				(int) padding);
		gridView.setHorizontalSpacing((int) padding);
		gridView.setVerticalSpacing((int) padding);
	}
}
